﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Staticage.Core {
    public static class Strings {
        public static string NullToEmpty(string @string) {
            return (@string == null) ? "" : @string;
        }

        public static string EmptyToNull(string @string) {
            return string.IsNullOrEmpty(@string) ? null : @string;
        }

        public static string ValueOf(object @object) {
            return @object == null ? "null" : @object.ToString();
        }

        public static string Format(string template, params object[] args) {
            template = ValueOf(template); // null -> "null"
            // start substituting the arguments into the '%s' placeholders
            StringBuilder builder = new StringBuilder(
                template.Length + 16 * args.Length);
            int templateStart = 0;
            int i = 0;
            while (i < args.Length) {
                int placeholderStart = template.IndexOf("%s", templateStart);
                if (placeholderStart == -1) {
                    break;
                }
                builder.Append(template.Substring(templateStart, placeholderStart));
                builder.Append(args[i++]);
                templateStart = placeholderStart + 2;
            }
            builder.Append(template.Substring(templateStart));

            // if we run out of placeholders, append the extra args in square braces
            if (i < args.Length) {
                builder.Append(" [");
                builder.Append(args[i++]);
                while (i < args.Length) {
                    builder.Append(", ");
                    builder.Append(args[i++]);
                }
                builder.Append(']');
            }
            return builder.ToString();
        }
    }
}
